#include "palyer.h"
#include <QtConcurrent/QtConcurrentRun>
#include <QProcess>
#include <QDir>
#include <QFileInfo>
#include <QLabel>

myPalyer::myPalyer(QObject *parent) : QObject(parent)
{

    //connect(this,SIGNAL(thumbnailGenerated(const QString&)),this,SLOT(updateVideoIcon(const QString&)));
}

//截图函数
void myPalyer::generateThumbnail(const QString &videoPath, const QString &thumbnailPath)
{
    QtConcurrent::run([=]() {
    QProcess process;
    QStringList args;
    args << "filesrc" << "location=" + videoPath
         << "!" << "decodebin"
         << "!" << "videoconvert"
         << "!" << "videoscale"
         << "!" << "video/x-raw,width=640,height=480"
         << "!" << "jpegenc"
         << "!" << "filesink" << "location=" + thumbnailPath;

    process.start("gst-launch-1.0", args);
    process.waitForFinished(-1);

    // 缩略图已生成，可以更新 UI
    emit thumbnailGenerated(videoPath,thumbnailPath);  // 假设你有一个信号
    });
}

//获取文件夹里所有的文件名并且截图
void myPalyer::getFilesInDirectory(const QString &folderPath)
{
    QDir dir(folderPath);
    if (!dir.exists()) {
        qDebug() << "file path not exist" << folderPath << endl;
        return;
    }

    // 获取当前目录下的所有文件（不包括子目录）
    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files);
    videoCount = fileInfoList.count();

    // 用于记录当前要处理的文件索引
    //uint8_t labelIndex = 0;

    for (const QFileInfo& fileInfo : fileInfoList) {
        QString filePath = fileInfo.absoluteFilePath();
        if(!processedFiles.contains(filePath))
        {
            // 该文件未处理过，生成缩略图
            generateThumbnail(filePath,"./images/" + changeFileExtension(filePath,"jpg"));//将mp4后缀改为jpg后缀放到第二个参数中
            qDebug() << "file path:" << filePath << endl;
            // 将文件加入已处理列表
            processedFiles.append(filePath);
        }

    }
}

//改变文件后缀名
QString myPalyer::changeFileExtension(const QString &oldPath, const QString &newExtension)
{
    QFileInfo fileInfo(oldPath);
    QString baseName = fileInfo.baseName();  // 获取不带后缀的文件名
    QString newFileName = baseName + "." + newExtension;  // 拼接新后缀
    return newFileName;
}

